#pragma once
#include <iostream>
#include <sys/epoll.h>
#include "LOG.hpp"
using namespace std;

class Epoller
{
private:
    bool HanderEvents(int fd, uint32_t events,int type)
    {
        struct epoll_event epv;
        epv.events = events;
        epv.data.fd = fd;
        int n = epoll_ctl(_epfd, type, fd, &epv);
        if (n < 0)
        {
            LOG(ERROR, "epoll_ctl fail,n: %d\n", n);
            return false;
        }
        LOG(INFO, "epoll_ctl success,n: %d\n", n);
        return true;
    }

public:
    Epoller()
    {
        _epfd = epoll_create(128);
        if (_epfd < 0)
        {
            LOG(ERROR, "epoll_create fail: %d\n", _epfd);
            return;
        }
        LOG(INFO, "epoll_create success: %d\n", _epfd);
    }
    bool AddEvents(int fd, uint32_t events)
    {
        return HanderEvents(fd,events,EPOLL_CTL_ADD);
    }
    bool ModEvents(int fd, uint32_t events)
    {
        return HanderEvents(fd,events,EPOLL_CTL_MOD);
    }
    bool DelEvents(int fd)
    {
        return epoll_ctl(_epfd,EPOLL_CTL_DEL,fd,nullptr);
    }
    int Wait(struct epoll_event epvs[], int maxnum, int timeout)
    {
        int n = epoll_wait(_epfd, epvs, maxnum, timeout);
        return n;
    }
    ~Epoller()
    {
        if (_epfd >= 0)
        {
            close(_epfd);
        }
    }

private:
    int _epfd;
};